#include "dictionary.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int Dictionary_Create(Dictionary *dic)
{
	dic->Count = 0;
	dic->Lista = NULL;
    return 0;
}

int Dictionary_Destroy(Dictionary *dic)
{
    Nodo *aux;
    while (dic->Lista != NULL) {
          aux = dic->Lista;
          dic->Lista = dic->Lista->nxt;
          free(aux->key);
          free(aux->value);
          free(aux);
    }
    dic->Count = 0;
    dic->Lista = NULL;
    return 0;
}

void Dictionary_Add(Dictionary *dic, const char * aKey, const char * aValue)
{
	Nodo *aux;
	Nodo *New = (Nodo *)malloc((sizeof(Nodo)));
	New->key = (char *) malloc((sizeof(char))* (strlen(aKey) + 1));
	New->value = (char *) malloc((sizeof(char))* (strlen(aValue) + 1));
	New->nxt = NULL;
    strcpy(New->key, aKey);
    strcpy(New->value, aValue);

	if (dic->Lista == NULL)
		dic->Lista = New;
	else {
		aux = dic->Lista;
		while (aux->nxt != NULL)
			aux = aux->nxt;
		aux->nxt = New;
	 }
	dic->Count++;
}

int Dictionary_Index(Dictionary *dic, const char * key, char * output)
{
	Nodo *aux;
	aux = dic->Lista;
	while ((aux != NULL) && (strcmp(aux->key , key) != 0))
		aux = aux->nxt;
	if (aux != NULL) {
		if (output != NULL)
			strcpy(output, aux->value);
		return 1;
	}
	return -1;
}

int Dictionary_SetKey(Dictionary * dic, const char * key, const char * input)
{
	Nodo *aux;
	aux = dic->Lista;
	while ((aux != NULL) && (strcmp(aux->key , key) != 0))
		aux = aux->nxt;
	if (aux != NULL) {
//		free(aux->value);
//		aux->value = (char *) malloc((sizeof(char))* strlen(input));
		aux->value = (char *) realloc(aux->value, (sizeof(char)) * (strlen(input) + 1));
		strcpy(aux->value, input);
		return 0;
	}
	return -1;
}

int Dictionary_AtElement(Dictionary *dic, int id, char * output)
{
	Nodo *aux;
	int i = 0;
	aux = dic->Lista;
	while ((aux != NULL) && (i < id)) {
		aux = aux->nxt;
		i++;
	}
	if (aux != NULL) {
		strcpy(output, aux->value);
		return 1;
	}
	return -1;
}

int Dictionary_Delete(Dictionary * dic, const char * key)
{
	if (dic->Count <= 0) return -1;
	Nodo *aux;
	Nodo *supr;
	aux  = dic->Lista;
	if (strcmp(dic->Lista->key, key) == 0)
	{
		supr = dic->Lista;
		dic->Lista = dic->Lista->nxt;
		free(supr->key);
		free(supr->value);
		free(supr);
		dic->Count--;
		return 0;
	}
	supr = dic->Lista->nxt;
	while ((supr != NULL) && (strcmp(supr->key , key) != 0))
	{
		aux  = supr;
		supr = supr->nxt;
	}
	if (supr != NULL)
	{
		aux->nxt = supr->nxt;
		free(supr->key);
		free(supr->value);
		free(supr);
		dic->Count--;
		return 0;
	}
	return -1;
}
